#include <stdio.h>

#include "cJSON.h"

char *msg =
"{                                      \
    \"name\": \"zhang3\",               \
    \"age\":  22,                       \
    \"weiWght\":      60.500000,        \
    \"address\":      {                 \
            \"country\":      \"China\",\
            \"zip-code\":     11111     \
    },                                  \
    \"skill\":        [\"C\", \"JAVA\", \"Python\"],\
    \"student\":      false             \
}"
;


//解析json数据
int main()
{
    cJSON* cjson_test = NULL;
    cJSON* cjson_name = NULL;
    cJSON* cjson_age = NULL;
    cJSON* cjson_weight = NULL;
    cJSON* cjson_address = NULL;
    cJSON* cjson_address_country = NULL;
    cJSON* cjson_address_zipcode = NULL;
    cJSON* cjson_skill = NULL;
    cJSON* cjson_student = NULL;
    int    skill_array_size = 0, i = 0;
    cJSON* cjson_skill_item = NULL;

    //解析整个json数据
    cjson_test = cJSON_Parse(msg);

    //根据键 name  age  weiWght得到 值
    cjson_name = cJSON_GetObjectItem(cjson_test,"name");
    cjson_age = cJSON_GetObjectItem(cjson_test,"age");
    cjson_weight = cJSON_GetObjectItem(cjson_test,"weiWght");

    printf("name:%s\n"
           "age:%d\n"
           "weiWght:%f\n",
           cjson_name->valuestring,
           cjson_age->valueint,
           cjson_age->valuedouble);

    //根据键  address  得到 值--json对象
    cjson_address = cJSON_GetObjectItem(cjson_test,"address");
    //再根据 json对象cjson_address 中的  键  country zip-code  得到值
    cjson_address_country = cJSON_GetObjectItem(cjson_address,"country");
    cjson_address_zipcode = cJSON_GetObjectItem(cjson_address,"zip-code");

    printf("country:%s\n"
           "zip-code:%d\n",
           cjson_address_country->valuestring,
           cjson_address_zipcode->valueint);

    //根据键 skill  得到 值 ---json数组
    cjson_skill = cJSON_GetObjectItem(cjson_test,"skill");

    printf("skill: [");

    //获取数组元素个数
    skill_array_size = cJSON_GetArraySize(cjson_skill);
    //遍历数组，获取数组每个元素
    for(int i=0; i<skill_array_size; i++)
    {
        cjson_skill_item = cJSON_GetArrayItem(cjson_skill,i);

        printf("%s ",cjson_skill_item->valuestring);
    }

    printf("]\n");

    //根据键 student 得到 值  ---bool类型
    cjson_student = cJSON_GetObjectItem(cjson_test,"student");

    printf("student:%d\n",cjson_student->valueint);


    //释放内存
    cJSON_Delete(cjson_test);

    return 0;
}
